import React, { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Checkbox, Popconfirm, DatePicker, InputNumber, FormInstance } from 'antd';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getPlanOrderList, deletePlanOrder } from '@/services/order/api';
import { history, useModel } from 'umi';
import { OptType, PlanOrderStatus } from '@/utils/constants';
import { PlusOutlined } from '@ant-design/icons';
import { isExits, showMsg, MsgType, formatDate, subtractDays, currentDate, setCache, getCache, parseDate, getDateValue, isSupportSticky } from '@/utils/utils';
import { ProFormFieldSet } from '@ant-design/pro-form';
import PermissionControl from '@/components/PermissionControl';
import './style.less';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import ChoicePatient from '@/components/ChoicePatient/list';

interface PlanOrderListProps {
  location?: any;
}

const PlanOrderList: React.FC<PlanOrderListProps> = (props) => {
  const { location } = props;
  const { query } = location;
  const { initialState } = useModel('@@initialState');
  

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();

  const [inputNo, setInputNo] = useState(''); // 身份证/病案号

  const [clickRow, setClickRow] = useState(query?.order_id || ''); // 当前选中的行编号，用于定位颜色

  const columns: ProColumns<ORDERAPI.PlanOrderItem>[] = [
    {
      title: '计划创建时间',
      dataIndex: 'plan_create_time',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest },form) => {
        if (type === 'form') {
          return null;
        }
        return <ProFormFieldSet>
            <DatePicker allowClear={false} style={{width: '100%'}} />
            <span style={{padding: '0 5px'}}>-</span>
            <DatePicker allowClear={false} style={{width: '100%'}} />
          </ProFormFieldSet>
      }
    },
    {
      title: '身份证/病案号',
      dataIndex: 'admission_num',
      hideInTable: true,
      fieldProps: {
        placeholder: '输入身份证/病案号',
      },
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <ChoicePatient
            caseNoKey={initialState?.canAll ? 'out_case_no' : 'case_no'}
            showMore
            onChoice={(e) => setInputNo(e.visit_no)}
          />
        );
      },
    },
    {
      title: '患者姓名',
      dataIndex: 'patient_name',
      hideInTable: true,
      fieldProps: {
        placeholder: '输入患者姓名',
      }
    },
    {
      title: '计划执行状态',
      dataIndex: 'plan_status',
      hideInTable: true,
      valueType: 'select',
      valueEnum: PlanOrderStatus
    },
    {
      title: '待结算金额',
      dataIndex: 'wait_sett_price',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest },form) => {
        if (type === 'form') {
          return null;
        }
        return (<ProFormFieldSet style={{gap: 2}}>
            <InputNumber style={{width: '100%'}} placeholder="最小值"/>
            <span style={{padding: '0 5px'}}>-</span>
            <InputNumber style={{width: '100%'}} placeholder="最大值"/>
          </ProFormFieldSet>
        );
      }
    },
    {
      title: '姓名',
      dataIndex: 'patient_name',
      width: 90,
      search: false
    },
    {
      title: '住院号',
      dataIndex: 'admission_num',
      width: 80,
      search: false
    },
    {
      title: '床位号',
      dataIndex: 'bed_no',
      width: 80,
      search: false
    },
    {
      title: '计划创建时间',
      dataIndex: 'create_date',
      width: 150,
      search: false,
      render: (_, record: ORDERAPI.PlanOrderItem) => {
        return record.create_date + ' ' + record.create_time;
      }
    },
    {
      title: '项目数',
      dataIndex: 'project_num',
      width: 60,
      align: 'right',
      search: false
    },
    {
      title: '已出账金额',
      dataIndex: 'out_price',
      align: 'right',
      valueType: 'money',
      width: 90,
      search: false
    },
    {
      title: '已结算金额',
      dataIndex: 'sett_price',
      align: 'right',
      valueType: 'money',
      width: 90,
      search: false
    },
    {
      title: '待结算金额',
      dataIndex: 'wait_price',
      align: 'right',
      valueType: 'money',
      width: 90,
      search: false
    },
    {
      title: '责任人',
      dataIndex: 'create_user_name',
      width: 70,
      search: false
    },
    {
      title: '责任人',
      dataIndex: 'order_person',
      hideInTable: true,
      fieldProps: {
        placeholder: '输入责任人',
      }
    },
    {
      title: '搜索结果不包括',
      dataIndex: 'not_status_list',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        if (type === 'form') {
          return null;
        }
        return <Checkbox.Group 
          options={
            [
              {
                label: '已出院',
                value: 'F'
              },
              {
                label: '已停止',
                value: 'S'
              }
            ]} />
      }
    },
    {
      title: '计划状态',
      dataIndex: 'plan_status',
      width: 90,
      search: false,
      render: (_, record: ORDERAPI.PlanOrderItem) => {
        return PlanOrderStatus[record.plan_status as string];
      }
    },
    {
      title: '操作',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      width: 120,
      align: 'center',
      valueType: 'option',
      render: (_, record) => {
        // 计划状态W：待创建，C：已创建，R：执行中，S：已停止，F：已出院 ,
        const { plan_status } = record;
        if (plan_status === 'C') {
          return [
            <PermissionControl action_id="400401002">
            <a key="edit" onClick={() => {
              onEdit(record);
            }}>查看/编辑</a></PermissionControl>,
            <PermissionControl action_id="400401003">
              <Popconfirm 
                key="delete"
                placement="topLeft"
                okText="确认删除"
                cancelText="再想想"
                onConfirm={async () => {
                  try {
                    await deletePlanOrder(record.order_id as string);
                    showMsg('已删除', MsgType.SUCCESS);
                    actionRef.current?.reload();
                  } catch (error) {
                    showMsg(error?.data?.errmsg);
                  }
                }}
                title="删除后计划将无法恢复，是否继续？">
                <a>删除</a>
              </Popconfirm>
            </PermissionControl>
          ]
        }

        if (plan_status === 'F' && isExits('400401002')) {
          return [
            <a key="edit" onClick={() => {
              onEdit(record);
            }}>查看</a>
          ]
        }
        if (isExits('400401002')) {
          return [
            <a key="edit" onClick={() => {
              onEdit(record);
            }}>查看/编辑</a>
          ]
        }
      } 
    }
  ];

  // 编辑/查看
  const onEdit = (record: ORDERAPI.PlanOrderItem) => {
    history.push({
      pathname: '/order/planOrder/detail', 
      query: { order_id: record.order_id || ''}
    });
  }

  useEffect(() => {
    if (query?.from !== 'detail') {
      setCache('plan_order', '');
      formRef.current?.setFieldsValue({
        plan_create_time: [subtractDays(7), '', currentDate()],
        not_status_list: ['F', 'S']
      });
      formRef.current?.submit();
      return
    }
    let searchCondition = getCache('plan_order');
    searchCondition = JSON.parse(searchCondition || '{}');

    formRef.current?.setFieldsValue({
      plan_create_time: [
        searchCondition.begin_date ? parseDate(searchCondition.begin_date) : subtractDays(7), 
        '', 
        searchCondition.end_date ? parseDate(searchCondition.end_date) : currentDate()
      ],
      admission_num: searchCondition.admission_num,
      patient_name: searchCondition.patient_name,
      plan_status: searchCondition.plan_status,
      order_person: searchCondition.order_person,
      wait_sett_price: [
        searchCondition.begin_wait_price,
        '',
        searchCondition.end_wait_price
      ],
      not_status_list: searchCondition.not_status_list
    });
    formRef.current?.submit();
  }, [])
   
  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} className="plan-order-container" breadcrumb={{}}>
      <ProTable<ORDERAPI.PlanOrderItem, ORDERAPI.PlanOrderItem & COMMON.PageParams & {plan_create_time?: string[]; wait_sett_price?: number[]; not_status_list?: string[]}>
        rowKey="order_id"
        options={false}
        bordered
        formRef={formRef}
        manualRequest={true}
        actionRef={actionRef}
        request={async (params) => {
          try {
            const { plan_create_time, wait_sett_price } = params;
            if (plan_create_time?.length) {
              // @ts-ignore
              params.begin_date = plan_create_time[0] && formatDate(plan_create_time[0], 'YYYYMMDD');
              // @ts-ignore
              params.end_date = plan_create_time[2] && formatDate(plan_create_time[2], 'YYYYMMDD');
              delete params.plan_create_time;
            }
            if (wait_sett_price) {
              // @ts-ignore
              params.begin_wait_price = wait_sett_price[0];
              // @ts-ignore
              params.end_wait_price = wait_sett_price[2];
              delete params.wait_sett_price;
            }
            if (inputNo.length >= 15) {
              params.identity_no = inputNo;
              params.admission_num = '';
            } else {
              params.identity_no = '';
              params.admission_num = inputNo;
            }
            for (const prop in params) {
              if (!params[prop]) {
                delete params[prop];
              }
            }
            const searchCondition = {}
            for (const prop in params) {
              if (!['current', 'pageSize'].includes(prop)) {
                searchCondition[prop] = params[prop];
              }
            }
            setCache('plan_order', JSON.stringify(searchCondition));
            if (plan_create_time && plan_create_time[0] && plan_create_time[2]) {
              if (getDateValue(plan_create_time[0]) > getDateValue(plan_create_time[2])) {
                showMsg('计划创建结束时间不能早于开始时间', MsgType.INFO);
                return {
                  data: [],
                  success: true,
                  total: 0
                } 
              }
            }
            if (wait_sett_price && wait_sett_price[0] && wait_sett_price[2]) {
              if (wait_sett_price[0] > wait_sett_price[2]) {
                showMsg('待结算金额最大值不能小于最小值', MsgType.INFO);
                return {
                  data: [],
                  success: true,
                  total: 0
                } 
              }
            }
            const data = await getPlanOrderList(params);
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num
            }
          } catch (error) {
            showMsg(error?.data?.errmsg, MsgType.ERROR);
            return {
              data: [],
              success: true,
              total: 0
            }
          }
        }}
        search={{
          span: 8,
          labelWidth: 110,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [<PermissionControl action_id="400401000">{dom}</PermissionControl>];
          }
        }}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'add',
                label: <PermissionControl action_id="400401001">
                  <Button 
                    onClick={() => {
                      history.push({
                        pathname: '/order/planOrder/detail',
                        query: {
                          type: OptType.ADD
                        }
                      });
                    }} 
                    icon={ <PlusOutlined />}
                    type="primary">
                    创建计划
                  </Button>
                </PermissionControl>
              }
            ]
          }
        }}
        pagination={{
          showQuickJumper: true
        }}
        columns={columns}
        scroll={{ 
          scrollToFirstRowOnChange: true,
          x: 1000 
        }}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.order_id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.order_id === clickRow ? 'tableRowClick' : ''
        }}
      />
    </PageContainer>
  );
};
export default PlanOrderList;
